import { requestSDK } from "@ct/iframe-connect-sdk";
import { setToken } from "@/utils/common";
const user = {
  state: {
    name: "",
    avatar: "",
    userType: "",
    roles: [],
    permissions: [],
    userInfo: {},
    userDeptTreeList: {},
  },

  mutations: {
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_USERDEPT_TREE_LIST: (state, userDeptTreeList) => {
      state.userDeptTreeList = userDeptTreeList;
    },
  },

  actions: {
    // 获取用户信息
    async GetInfo({ commit }) {
      const res = await requestSDK("getInfo");
      const userInfo = res.user;
      if (userInfo?.roles && userInfo.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        commit("SET_ROLES", userInfo.roles);
      } else {
        commit("SET_ROLES", ["ROLE_DEFAULT"]);
      }
      window.bonreeJsBridge?.setUserID(res.user.userName);
      localStorage.setItem("$loginInfo", JSON.stringify(userInfo));
      setToken(res.user.token);
      commit("SET_USERINFO", userInfo);
      commit("SET_USER_TYPE", userInfo.userType);
      commit("SET_NAME", userInfo.nickName);
      commit("SET_AVATAR", userInfo.avatar);
    },
    async getPermissionsByTarget({ commit }) {
      const res = await requestSDK("getPermissionsByTarget");
      commit("SET_PERMISSIONS", res.permissions);
    },
  },
};

export default user;
